#!/usr/bin/env ruby

dir = "."
count = 0

while true
  a = `find #{dir} -name "*.java" -type f | sort -r`.split
  if a.length > 0
    break
  else
    dir += "/.."
  end

  break if count > 3
  count += 1
end

if ARGV.length > 0 and File.directory? ARGV[0]
  curdir = ARGV[0]
else
  curdir = `pwd`
end

initialDir = `pwd`
Dir.chdir(curdir)

unless not a
  a.each do |fn|
    File.open(fn) do |f|
      doc = f.readlines.join
      rez = doc.scan(/package\s+(\S+?);/)
      if rez.length > 0
        package = rez[0][0]
        Dir.chdir File.dirname(fn)

        cd=`pwd`
        pos = curdir.length
        (0...curdir.length).each do |i|
          if cd.length <= i or cd[i] != curdir[i]
            pos=i
            break
          end
        end

        puts cd
        puts curdir

        puts toAdd = curdir[pos,curdir.length].gsub(/\//, '.')
        puts toSubstract = cd[pos,cd.length].gsub(/\//, '.')
        puts package.sub(/#{toSubstract.gsub(/\./, "\\.")}$/, "") + toAdd

        `cd #{initialDir.gsub(/ /, "\ ")}`
        exit 0
      end
    end
  end
end
